(function(){
    angular.module('feibo.teacher.controller').controller('TeacherContractCalendarController', TeacherContractCalendarController);

    TeacherContractCalendarController.$inject = ['$stateParams', 'TeacherService', 'kvMap'];

    function TeacherContractCalendarController($stateParams, TeacherService, kvMap){
        var vm = this;

        vm.kvMap = {
            shiftTimeSlotType: kvMap.shiftTimeSlotType,
            buyoutTeacherCalendarConflict: kvMap.buyoutTeacherCalendarConflict
        };

        vm.data = {
            schoolId: undefined,
            buyoutTeacherId: $stateParams.buyout_teacher_id,
            teacher: undefined,
            bindTimeItemsData: [],
            rowTimePoints: [],  // 横向时间点
            lowDatePoints: [],  // 纵向日期点
            buyoutTeacherCalendar: undefined,  // 老师日历冲突情况
            buyoutTimePoint: {},
            search: {
                clearStart: undefined,
                clearEnd: undefined,
                start: undefined,
                end: undefined,
                tempLowDatePoints: undefined,
                clearTempLowDatePoints: undefined,
                isCheck: false
            },
            weeks: [{
                zh: '周一',
                en: 'Mon'
            },{
                zh: '周二',
                en: 'Tue'
            },{
                zh: '周三',
                en: 'Wed'
            },{
                zh: '周四',
                en: 'Thur'
            },{
                zh: '周五',
                en: 'Fri'
            },{
                zh: '周六',
                en: 'Sat'
            },{
                zh: '周日',
                en: 'Sun'
            }]
        };

        vm.initData = function(){
            vm.getBuyoutTeacher();
            vm.initDatetimepicker(['#datetimepicker1', '#datetimepicker2', '#datetimepicker3', '#datetimepicker4']);
        };

        vm.initDatetimepicker = function(selectorArr){
            if(angular.isArray(selectorArr)){
                selectorArr.forEach(function(val){
                    $(val).datetimepicker({
                        lang: 'ch',
                        format: 'Y-m-d',
                        timepicker: false,
                        yearStart: 2000,
                        yearEnd: 2050,
                        step: 10
                    });
                });
            }
        };

        vm.createLowDatePoints = function(start, end){
            var lowDatePoints = [];
            var currentTime = (new Date(start.replace(/-/g, '/') + ' 00:00:00')).getTime();
            var endTime = (new Date(end.replace(/-/g, '/') + ' 00:00:00')).getTime();
            var y, m, d, w, currentDate;

            while(endTime >= currentTime){
                currentDate = new Date(currentTime);
                currentTime = currentDate.getTime();
                currentTime += 86400000;
                y = currentDate.getFullYear();
                m = currentDate.getMonth() + 1;
                d = currentDate.getDate();
                w = currentDate.getDay();
                m = m > 9 ? m : '0' + m;
                d = d > 9 ? d : '0' + d;
                w = w > 0 ? w - 1 : 6;

                lowDatePoints.push({
                    date: y + '-' + m + '-' + d,
                    week: w
                });
            }

            return lowDatePoints;
        };

        vm.checkCurrentCalendar = function(){
            vm.getBuyoutTeacherCalendar();
        };

        // 清空日历数据
        vm.clearCalendarData = function(){
            var search = vm.data.search;

            search.clearTempLowDatePoints.forEach(function(val){
                var $li = $('#' + val.date);
                $li.find('span[data-conflict]').html('').attr('data-conflict', '0');
            });
            vm.data.search.isCheck = false;
        };

        // 获取需要填充的时间点
        vm.getFillCalendar = function(){
            var returnDate = {
                fillArr: [],
                noConflictArr: []
            };
            var buyoutTeacherCalendarConflict = vm.kvMap.buyoutTeacherCalendarConflict.vkMap;
            var noConflictKeyArr = [
                buyoutTeacherCalendarConflict.noConflict,
                buyoutTeacherCalendarConflict.notBuyout,
                buyoutTeacherCalendarConflict.absenceBuyout
            ];
            vm.data.search.tempLowDatePoints.forEach(function(val){
                var id = val.date;
                var $li = $('#' + id);

                // 要添加的时间点
                $li.find('span[readonly][data-conflict=0]').each(function(key, node){
                    var className = node.className;
                    returnDate.fillArr.push(id + ' ' + className.substr(0, 2) + ':' + className.substr(-2));
                });

                // 要修改的可用时间点  noConflictKey: 1, notBuyout: 8, absenceBuyout: 9
                noConflictKeyArr.forEach(function(key){
                    $li.find('span[readonly][data-conflict=' + key + ']').each(function(key, node){
                        var className = node.className;
                        returnDate.noConflictArr.push(id + ' ' + className.substr(0, 2) + ':' + className.substr(-2));
                    });
                });
            });
            return returnDate;
        };

        // 获取冲突的时间点
        vm.getConflictCalendar = function(){
            var returnObj = {
                dateArr: [],
                unusableDateArr: []
            };
            // var returnArr = [];
            var conflict = vm.kvMap.buyoutTeacherCalendarConflict.vkMap;
            vm.data.search.clearTempLowDatePoints.forEach(function(val){
                var id = val.date;
                $('#' + id).find('span[readonly][data-conflict]').each(function(key, node){
                    var dataConflict = node.getAttribute('data-conflict');
                    // [4, 6, 9]
                    // if(dataConflict && [conflict.conflictDueToBO, conflict.success, conflict.absenceBuyout].indexOf(Number(dataConflict)) !== -1){
                    //     var className = node.className;
                    //     returnObj.dateArr.push(id + ' ' + className.substr(0, 2) + ':' + className.substr(-2));
                    // }
                    if(dataConflict){
                        var className = node.className;
                        var pushData = id + ' ' + className.substr(0, 2) + ':' + className.substr(-2);
                        // [4, 6]
                        if([conflict.conflictDueToBO, conflict.success].indexOf(Number(dataConflict)) !== -1){
                            returnObj.dateArr.push(pushData);
                        // [9]
                        }else if([conflict.absenceBuyout].indexOf(Number(dataConflict)) !== -1){
                            returnObj.unusableDateArr.push(pushData);
                        }
                    }
                });
            });
            return returnObj;
        };

        // 填充时间点
        vm.fillCalendar = function(){
            var data = vm.data;
            var fillData = vm.getFillCalendar();
            var postConfig = {
                funcName: 'fillCalendar',
                successMsg: 'Fill Calendar Success',
                errorMsg: 'Fill Calendar Error',
                showLoadLayer: false,
                httpPostData: {
                    teacher_id: data.teacher.teacher_id,
                    school_id: data.schoolId,
                    date: fillData.fillArr,
                    exist_date: fillData.noConflictArr
                }
            };

            TeacherService.fillCalendar(postConfig).then(function(returnedData){
                if(returnedData.success){
                    vm.getBuyoutTeacherCalendar();
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        // 清空
        vm.clearCalendar = function(){
            var search = vm.data.search;
            search.clearTempLowDatePoints = vm.createLowDatePoints(search.clearStart, search.clearEnd);
            var conflict = vm.getConflictCalendar();
            var postConfig = {
                funcName: 'clearCalendar',
                successMsg: 'Clear Calendar Success',
                errorMsg: 'Clear Calendar Error',
                showLoadLayer: false,
                httpPostData: {
                    teacher_id: vm.data.teacher.teacher_id,
                    date: conflict.dateArr,
                    unusable_date: conflict.unusableDateArr
                }
            };

            if(postConfig.httpPostData.date.length === 0){
                vm.clearCalendarData();
                return;
            }

            var layerIndex = layer.confirm('Clear Calendar ' + search.clearStart + '－－' + search.clearEnd, {
                btn: ['确定','取消']
            }, function(){
                layer.close(layerIndex);
                TeacherService.clearCalendar(postConfig).then(function(returnedData){
                    if(returnedData.success){
                        vm.clearCalendarData();
                    }
                }).catch(function(error){
                    console.error(error);
                });
            });
        };

        // 获取买断老师冲突时间点
        vm.getBuyoutTeacherCalendar = function(){
            var queryConfig = {
                funcName: 'getBuyoutTeacherCalendar',
                // container: data,
                // propName: 'buyoutTeacherCalendar',
                propChain: ['data'],
                showLoadLayer: false,
                urlPlaceholder: {
                    buyout_teacher_id: vm.data.buyoutTeacherId
                }
            };

            TeacherService.getBuyoutTeacherCalendar(queryConfig).then(function(returnedData){
                var search = vm.data.search;
                if(returnedData.success){
                    var data = returnedData.data;
                    var tempTimePoint = vm.createLowDatePoints(search.start, search.end);

                    // 先清空 再 check
                    search.clearTempLowDatePoints = tempTimePoint;
                    vm.clearCalendarData();
                    search.tempLowDatePoints = tempTimePoint;
                    search.tempLowDatePoints.forEach(function(val){
                        var id = val.date;
                        var $li = $('#' + id);
                        var prefix;
                        try{
                            prefix = vm.data.teacher.buyout_teacher_pack.buyout_teacher_contract.school.prefix;
                        }catch(e){
                            prefix = 'XXX';
                        }
                        if(data[id]){
                            Object.keys(data[id]).forEach(function(className){
                                $li.find('span.' + className.replace(':', '') + '[readonly]').
                                        attr('data-conflict', data[id][className][0]).html(data[id][className][1]);
                            });
                        }

                        $li.find('span[readonly][data-conflict=0]').html(prefix);
                        $li.find('span[readonly][data-conflict=1]').html(prefix);
                    });

                    vm.data.search.isCheck = true;
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        // 获取买断老师
        vm.getBuyoutTeacher = function(){
            var data = vm.data;
            var queryConfig = {
                funcName: 'getBuyoutTeacher',
                container: data,
                propName: 'teacher',
                propChain: ['data'],
                showLoadLayer: false,
                urlPlaceholder: {
                    buyout_teacher_id: data.buyoutTeacherId
                }
            };

            TeacherService.getBuyoutTeacher(queryConfig).then(function(returnedData){
                if(returnedData.success){

                    vm.getClassMiniType(returnedData.data.fb_shift_type_id);
                    // 根据开始时间和结束时间生成纵向日期点
                    var buyout_teacher_pack = returnedData.data.buyout_teacher_pack;
                    var start = data.search.start = data.search.clearStart = buyout_teacher_pack.start_date;
                    var end = data.search.end = data.search.clearEnd = buyout_teacher_pack.end_date;
                    vm.data.lowDatePoints = vm.createLowDatePoints(start, end);
                    vm.data.schoolId = buyout_teacher_pack.buyout_teacher_contract.school_id;
                }
            }).catch(function(error){
                console.error(error);
            });
        };

        // 获取小类
        vm.getClassMiniType = function(id){
            var data = vm.data;
            var queryConfig = {
                funcName: 'getClassMiniType',
                propChain: [],
                showLoadLayer: false,
                urlPlaceholder: {
                    id: id
                }
            };

            TeacherService.getClassMiniType(queryConfig).then(function(returnedData){
                if(returnedData.success){
                    var tempTimePoint = {};
                    var bindTimeItemsData = data.bindTimeItemsData;

                    if(returnedData.data.shift_time_slot){
                        returnedData.data.shift_time_slot.forEach(function(val){
                            var time_slot = val.time_slot.substring(0, val.time_slot.lastIndexOf(':'));
                            if(val.type === vm.kvMap.shiftTimeSlotType.vkMap.work){
                                // 横向时间点
                                if(vm.data.rowTimePoints.indexOf(time_slot) === -1){
                                    vm.data.rowTimePoints.push(time_slot);
                                }

                                // 买断时间点对象 用于给每个买断时间点打标记
                                if(data.buyoutTimePoint[val.day_of_week]){
                                    data.buyoutTimePoint[val.day_of_week][time_slot] = true;
                                }else {
                                    data.buyoutTimePoint[val.day_of_week] = {
                                        [time_slot]: true
                                    };
                                }

                                // 临时时间点对象
                                if(angular.isArray(tempTimePoint[val.day_of_week])){
                                    tempTimePoint[val.day_of_week].push(val);
                                }else {
                                    tempTimePoint[val.day_of_week] = [val];
                                }
                            }
                        });

                        vm.data.rowTimePoints.sort(function(a, b){
                            return a >= b ? 1 : -1;
                        });
                        $('#time-calendar-container').css('min-width', 78 + 36 + 66 * vm.data.rowTimePoints.length + 24);
                    }

                    // 基于开始时间生成指定分钟后的结束时间
                    function baseTimePoint(start, step){
                        var baseDate = new Date('2017/01/01 ' + start);
                        var h = baseDate.getHours();
                        var m = baseDate.getMinutes();
                        var mTotle = step + h * 60 + m;
                        m = mTotle % 60;
                        h = mTotle / 60;
                        baseDate.setHours(h);
                        baseDate.setMinutes(m);
                        h = baseDate.getHours();
                        m = baseDate.getMinutes();
                        h = h > 9 ? h : '0' + h;
                        m = m > 9 ? m : '0' + m;

                        return h + ':' + m;
                    }

                    // 将时间点数组转换成时间段数组
                    function conversionTime(timeArr){
                        var returnArr = [];
                        var valve = true;
                        var temp, data;

                        while(timeArr.length){
                            if(valve){
                                temp = timeArr.splice(0, 1);
                                data = {
                                    type: temp[0].type,
                                    start_time: baseTimePoint(temp[0].time_slot, 0),
                                    end_time: baseTimePoint(temp[0].time_slot, 30)
                                };
                            }

                            valve = true;
                            timeArr.forEach(function(v, i){

                                if(v.type === vm.kvMap.shiftTimeSlotType.vkMap.work){
                                    var start = (new Date('2017/01/01 ' + data.start_time)).getTime();
                                    var end = (new Date('2017/01/01 ' + data.end_time)).getTime();
                                    var slot = (new Date('2017/01/01 ' + v.time_slot)).getTime();

                                    if(start === slot){
                                        valve = false;
                                        timeArr.splice(i, 1);
                                    }else if(slot === start - 180000){
                                        valve = false;
                                        data.start_time = baseTimePoint(v.time_slot, 0);
                                        timeArr.splice(i, 1);
                                    }else if(slot === end){
                                        valve = false;
                                        data.end_time = baseTimePoint(v.time_slot, 30);
                                        timeArr.splice(i, 1);
                                    }
                                }
                            });
                            if(valve || timeArr.length === 0){
                                returnArr.push(data);
                            }
                        }

                        return returnArr;
                    }

                    for(var i = 0; i <= 6; i++){
                        if(tempTimePoint[i]){
                            if(tempTimePoint[i].length === 1){
                                bindTimeItemsData.push({
                                    day_of_week: i,
                                    shift_time_slot: [{
                                        type: tempTimePoint[i][0].type,
                                        start_time: baseTimePoint(tempTimePoint[i][0].time_slot, 0),
                                        end_time: baseTimePoint(tempTimePoint[i][0].time_slot, 30)
                                    }]
                                });
                            }else {
                                bindTimeItemsData.push({
                                    day_of_week: i,
                                    shift_time_slot: conversionTime(tempTimePoint[i])
                                });
                            }
                        }else {
                            bindTimeItemsData.push({
                                day_of_week: i,
                                shift_time_slot: []
                            });
                        }
                    }
                }
            }).catch(function(error){
                console.error(error);
            });
        };
    }
}());
